package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.util.FastDFSClient;
import com.changgou.file.util.FastDFSFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author: zhengke
 * @date: 2020/12/11
 * @return:
 * @description:
 */

@RestController
@RequestMapping("/file")
public class FileController {

    //在service实现类定义日志实例  --仿照goods模块 修改配置文件logback-spring.xml
    private Logger logger = LoggerFactory.getLogger(getClass());
    @PostMapping
    public Result upload(@RequestParam("file") MultipartFile file) {
        String fileName = null;
        try {
            fileName = file.getOriginalFilename();//获取文件名+后缀，即全名
            String extName = fileName.substring(fileName.lastIndexOf("."));//获取扩展名，即后缀
            byte[] fileContext = file.getBytes();//获取文件内容

            //构建一个FastDFSFile对象
            FastDFSFile fastDFSFile=new FastDFSFile(fileName, fileContext, extName);

            String[] uploadResult = FastDFSClient.upload(fastDFSFile);

            if(uploadResult!=null&&uploadResult.length==2){
                String groupName = uploadResult[0];//获取文件组名
                String remoteFilePath = uploadResult[1];//获取文件在存储服务器的远程存储路径
                //TODO 将路径存储到数据库表中

                String url=FastDFSClient.getTrackerUrl()+groupName+"/"+remoteFilePath;
                logger.info("上传成功，url：{}",url);
                return new Result(true,StatusCode.OK,"上传成功",url);//http://192.168.200.128:8080/group1/M00/00/00/wKjIgF_SRZGABIjdAAFOgnJ4Ktc87..jpg
            }else {
                logger.error("上传失败，fileName：{}",fileName);
                return new Result(false,StatusCode.ERROR,"上传失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("上传失败，fileName：{}",fileName);
            return new Result(false,StatusCode.ERROR,"上传失败");
        }

    }
}
